package com.wxcms.service.impl;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.wxcms.domain.DepEquipments;
import com.wxcms.domain.DodemWxCpUser;
import com.wxcms.domain.WxCpMyConfigStorage;
import com.wxcms.mapper.WxCpDepartDao;
import com.wxcms.mapper.WxCpMyConfigStorageDao;
import com.wxcms.mapper.WxCpUserDao;
import com.wxcms.service.BaseService;
import com.wxcms.service.MyWxCpService;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.cp.api.WxCpMessageHandler;
import me.chanjar.weixin.cp.api.WxCpMessageRouter;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpDepart;
import me.chanjar.weixin.cp.bean.WxCpMessage;
import me.chanjar.weixin.cp.bean.WxCpUser;
import me.chanjar.weixin.cp.bean.WxCpXmlMessage;
import me.chanjar.weixin.cp.bean.WxCpXmlMessage.ScanCodeInfo;
import me.chanjar.weixin.cp.bean.WxCpXmlOutMessage;
import me.chanjar.weixin.cp.bean.WxCpXmlOutNewsMessage;
import me.chanjar.weixin.cp.bean.WxCpXmlOutNewsMessage.Item;
import me.chanjar.weixin.cp.bean.WxCpXmlOutTextMessage;

@Service("MyWxCpService")  

public    class MyWxCpServiceImpl implements BaseService  ,  MyWxCpService{
	
	protected Logger log= Logger.getLogger(this.getClass());
	
    protected DodemWxServer wxCpService;
	HashMap<String , DodemWxServer> wxSMAP = new HashMap<String , DodemWxServer>();   
	
	protected WxCpMyConfigStorage config;
	
    @Autowired
    protected WxCpUserDao userdao;
	
    @Autowired
    protected WxCpDepartDao depdao;
	
	@Autowired
    protected WxCpMyConfigStorageDao configStorageDao;
	
    
	protected WxCpMessageRouter wxCpMessageRouter;
	
	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}
	protected	HttpServletRequest request;
	
	
	public WxCpMessageRouter getWxCpMessageRouter() {
		return wxCpMessageRouter;
	}
	@PostConstruct
	public void init(){
		
 		List<WxCpMyConfigStorage> config1=configStorageDao.getall();
 		//config=config1.get(0);
 		for(WxCpMyConfigStorage config : config1){
 
 			DodemWxServer	wxs= new DodemWxServer();
 			wxs.setWxCpConfigStorage( config);
 			wxSMAP.put(config.getProvince()+"+"+config.getToken(), wxs) ;
 			initRouter(wxs);	
 		}
 		
 		// 	wxCpService = new WxCpServiceImpl();
 		
 	//	wxCpService.setWxCpConfigStorage((WxCpConfigStorage) config);
 		
	//	initRouter();
	}
	
 	@Override
 	public Collection<DodemWxServer> getWxCpServices() {
 		// TODO Auto-generated method stub
 		return wxSMAP.values();
 	}
	
	@Override
	public DodemWxServer getWxCpServiceByPT(String province,String token) {
		// TODO Auto-generated method stub
		
// 		List<WxCpMyConfigStorage> config1=configStorageDao.getbyPT(province,token);
// 		config=config1.get(0);
// 		
// 		WxCpService	wxCpService = new WxCpServiceImpl();
// 		
// 		wxCpService.setWxCpConfigStorage((WxCpConfigStorage) config);  
	
		
    java.util.Iterator<Entry<String, DodemWxServer>> iter = wxSMAP.entrySet().iterator();
	while (iter.hasNext()) {
		Map.Entry entry = (Map.Entry) iter.next();
		Object key = entry.getKey();
		DodemWxServer val = (DodemWxServer) entry.getValue();
		log.debug(key+"====================="+val);
		log.debug( val.getConfig());
		log.debug(val.getConfig().getAccessToken());
	}
		
	wxCpService =wxSMAP.get(province+"+"+token);	
		
		return wxCpService;
	}
	//冲服务器 读取 所有应用的 id  name  PUID
	@Override
	public JSONObject syncAgentInfo(){
		JSONObject o= new JSONObject();
		
		List<WxCpMyConfigStorage> config1=configStorageDao.getall(); 
 		for(WxCpMyConfigStorage config : config1){
 			
 	 
 			JSONObject obj =getappinfo(config.getProvince(),config.getToken()); 
 			log.debug(obj+"==="+config.getProvince()+"==========+++++==========="+config.getToken());
	 		config.setName(obj.get("name").toString());
	 	    config.setIcon(obj.get("square_logo_url").toString().replace("/0", "/64"));
	 		 
 			configStorageDao.updateConfigByAgentid(config);
 			
 		}
		o.put("success", true);
		
		
		return o;
		
	}
	
	//根据配置读取单个 应用哪号的信息
	@Override
	public  JSONObject getappinfo( String province,  String token)  {
		
		DodemWxServer  myService=  getWxCpServiceByPT(province, token);
		String res = null;
		try {
		 
		//	System.out.println(((WxCpMyConfigStorage) myService.getConfig()).getProvince()+"==========+++++==========="+config.getToken());
			res = myService.get("https://qyapi.weixin.qq.com/cgi-bin/agent/get",
					"agentid=" + myService.getConfig().getAgentId());
		} catch (WxErrorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	 
		JSONObject obj = JSONObject.parseObject(res);

		return obj;
	}
//	@Override
//	public WxCpService getWxCpServiceByConfig(WxCpConfigStorage config) {
//		// TODO Auto-generated method stub
//		
//  
// 		
// 		wxCpService.setWxCpConfigStorage( config);  
//	 		 
//		return wxCpService;
//	}
	public void initRouter(WxCpService wxCpService) {

		WxCpMessageHandler handlertest = new WxCpMessageHandler() {

			public WxCpXmlOutMessage handle(WxCpXmlMessage wxMessage, Map<String, Object> context,
					WxCpService wxCpService, WxSessionManager sessionManager) throws WxErrorException {

				WxCpXmlOutTextMessage m = WxCpXmlOutMessage.TEXT().content("<a href='http://www.baidu.com'>文本链接</a>\n <a color=\"www.baidu.com\">文本颜色</a>").fromUser(wxMessage.getToUserName())
						.toUser(wxMessage.getFromUserName()).build();

				return m;
			}

		};
		WxCpMessageHandler handlepic = new WxCpMessageHandler() {

			public WxCpXmlOutMessage handle(WxCpXmlMessage wxMessage, Map<String, Object> context,
					WxCpService wxCpService, WxSessionManager sessionManager) throws WxErrorException {
				Logger.getLogger("ddd").info("===============" + wxMessage.toString());
				Item article1 = new WxCpXmlOutNewsMessage.Item();
				article1.setUrl("http://hxd.nat123.net/qyweix");
				article1.setPicUrl("http://hxd.nat123.net/qyweix/res/upload/1426908381642.jpg");
				// article1.setDescription("Is Really A Happy Day");
				article1.setTitle("" + wxMessage.getEventKey());

				WxCpXmlOutNewsMessage m = WxCpXmlOutMessage.NEWS().addArticle(article1)
						.fromUser(wxMessage.getToUserName()).toUser(wxMessage.getFromUserName()).build();

				return m;
			}

		};
		WxCpMessageHandler pringMsg = new WxCpMessageHandler() {

			public WxCpXmlOutMessage handle(WxCpXmlMessage wxMessage, Map<String, Object> context,
					WxCpService wxCpService, WxSessionManager sessionManager) throws WxErrorException {
				Logger.getLogger("ddd").info("dd===============\n\n\n" + wxMessage.toString());
                JSONObject  json=new JSONObject(context);
                log.info(json.toJSONString());

				return null;

			}
		};
		WxCpMessageHandler scanCodeMsg = new WxCpMessageHandler() {

			public WxCpXmlOutMessage handle(WxCpXmlMessage wxMessage, Map<String, Object> context,
					WxCpService wxCpService, WxSessionManager sessionManager) throws WxErrorException {
				ScanCodeInfo scodeinfo = wxMessage.getScanCodeInfo();
				StringBuffer sbuff=new  StringBuffer();
				Logger.getLogger("ddd").info("===============" + scodeinfo.getScanType());
				Logger.getLogger("ddd").info("===============" + scodeinfo.getScanResult());
			 
				sbuff.append("二维码识别结果为:\n").append(scodeinfo.getScanResult());
				 WxCpXmlOutTextMessage m = WxCpXmlOutMessage.TEXT().content(sbuff.toString()).fromUser(wxMessage.getToUserName())
				 		.toUser(wxMessage.getFromUserName()).build();
				
			/*	 WxCpMessage mX = WxCpMessage.TEXT().agentId(config.getAgentId()).toUser(wxMessage.getFromUserName()).content(sbuff.toString()).build(); 
				   wxCpService.messageSend(mX);
				   sbuff.setLength(0);//清空 
*/ 
				return m;

			}
		};
		
		WxCpMessageHandler equipList = new WxCpMessageHandler() {

			public WxCpXmlOutMessage handle(WxCpXmlMessage wxMessage, Map<String, Object> context,
					WxCpService wxCpService, WxSessionManager sessionManager) throws WxErrorException {

				StringBuffer sbuff=new  StringBuffer();
				 int len=0,index=0;
				 int maxSize=16;
				 
				List<DodemWxCpUser> lu = userdao.checkUser(wxMessage.getFromUserName());
				
				if(lu.size()>0){
					WxCpUser user=lu.get(0);
					String _ids="";
					String position=user.getPosition();
					if(position==null)
						position="";
					if(!position.contains("admin")){
						Integer[] ids=user.getDepartIds();
					      _ids=	StringUtils.join(ids,",");
					}
				    
				    List<DepEquipments> equips=  depdao.getequips(_ids);
				     len= equips.size();
				  
				     //由于发送的时间太长  ，导致request 提前消失   所以需要在这里暂存 
				     
				 String  scheme=request.getScheme();
				 
				 String  serverName=request.getServerName();
			 	    
				 /**
				  * 每次最多发送6个设备信息 文本信息是2k的限制。  主要是拼凑的url 占用了大量的空间  需要缩短url 借助中间url 来完成，不然设备数量会受限制
				  * 
				  * **** 特别说明 由于 oauth2buildAuthorizationUrl 的url 必须在微信中调用 所以采用中间url 的方法不可行
				  * **/
			    for(int i=0;i<len;++i){
				    	 DepEquipments eq=equips.get(i);
				    	  String _ul=scheme + "://" + serverName+"/qyweix/mx/"+eq.getPuid();
	
				 	 	//  String _ul=scheme+ "://" + serverName+"/qyweix/mindex?puid="+eq.getPuid();
				    //      String _wxul= wxCpService.oauth2buildAuthorizationUrl(_ul,"test");
				    	 sbuff.append("<a href=\""+_ul+"\" >"+eq.getName()+"</a>").append("\n").append("\n");
	//				     	 sbuff.append( eq.getName()).append("\n");
				     	 index=i+1;
				     	 
				     	 if(((i+1)%maxSize)==0){
				     		
							  // WxCpMessage m = WxCpMessage.NEWS().agentId("2").toParty(depids).addArticle(article1).build();
				     		 String static_info= String.format("设备总数：%d\n当前计数：%d-%d\n———————————————\n", len,(index+1)-maxSize,index)+sbuff.toString();
				     		   log.info(static_info);
							 WxCpMessage mX = WxCpMessage.TEXT().agentId(config.getAgentId()).toUser(wxMessage.getFromUserName()).content(static_info).build(); 
							 wxCpService.messageSend(mX);
							 sbuff.setLength(0);//清空
				     	 }
			     	
			    } 
 

				}else{
					sbuff.append("设备信息获取失败,请联系管理员！");
				}
				   
				   int begin=(index+1)-maxSize;
				   
				   if(len<=maxSize) 
					   begin=1;
				
				       String static_info= String.format("设备总数:%d\n当前计数：%d-%d\n———————————————\n", len,begin,index)+sbuff.toString();
				     
		    		   log.info(static_info);
		    		   
		    		   WxCpMessage mX = WxCpMessage.TEXT().agentId(config.getAgentId()).toUser(wxMessage.getFromUserName()).content(static_info).build(); 
					   wxCpService.messageSend(mX);
					   sbuff.setLength(0);//清空 
						 
//					   WxCpXmlOutTextMessage m = WxCpXmlOutMessage.TEXT().content(static_info).fromUser(wxMessage.getToUserName())
//							.toUser(wxMessage.getFromUserName()).build();

				return null;
			}
		};
		
		WxCpMessageHandler wxmenbers = new WxCpMessageHandler() {

			public WxCpXmlOutMessage handle(WxCpXmlMessage wxMessage, Map<String, Object> context,
					WxCpService wxCpService, WxSessionManager sessionManager) throws WxErrorException {
 

				StringBuffer sbuff=new  StringBuffer();
			 
				List<DodemWxCpUser> lu = userdao.checkUser(wxMessage.getFromUserName());
				if(lu.size()>0){
					WxCpUser user=lu.get(0);
				 
					Integer[] ids=user.getDepartIds();
					for(Integer id:ids){
						String _id=id.toString();
				      sbuff.append("———————————————\n");
					  sbuff.append( depdao.getdepname(_id)).append("\n");
					  sbuff.append("———————————————\n");
					  List<WxCpUser> us=  userdao.getUsers(_id);
					  int len=us.size();
					   for (int i=0;i<len;++i){
						   WxCpUser u=us.get(i);
						   sbuff.append(u.getName()).append(" ").append(u.getMobile()).append("\n");   
					  }
					  
					}
					
				}else{
					sbuff.append("成员信息获取失败,请联系管理员！");
				}
			     log.info(sbuff.toString());
			//	WxCpXmlOutTextMessage m = WxCpXmlOutMessage.TEXT().content(sbuff.toString()).fromUser(wxMessage.getToUserName())
			//			.toUser(wxMessage.getFromUserName()).build();
				
			   WxCpMessage mX = WxCpMessage.TEXT().agentId(config.getAgentId()).toUser(wxMessage.getFromUserName()).content(sbuff.toString()).build(); 
			   wxCpService.messageSend(mX);
			   sbuff.setLength(0);//清空 
				
			return null;

			}
		};

		wxCpMessageRouter = new WxCpMessageRouter(wxCpService);
		wxCpMessageRouter// .agentId(2)
				// 4个条件必须全部匹配的路由规则 // .msgType(WxConsts.XML_MSG_TEXT).event(WxConsts.EVT_SUBSCRIBE).eventKey("EVENT_KEY")
				// 每次进入的时候都会发送一个 event -》enter_agent 但是eventkey 是空的 // .rContent("content正则表达式")
				.rule().async(false).handler(pringMsg).next()
				.rule().async(false).event(WxConsts.EVT_CLICK.toLowerCase()).eventKey("wx_equipList").handler(equipList).end()
				.rule().async(false).event(WxConsts.EVT_CLICK.toLowerCase()).eventKey("wx_menber").handler(wxmenbers).end()
				.rule().async(false).content("图片").handler(handlepic).end()
				.rule().async(false).content("哈哈").handler(handlertest).end()
				.rule().async(false).event(WxConsts.BUTTON_SCANCODE_WAITMSG).handler(scanCodeMsg).end();
			//	.rule().async(false).event(WxConsts.BUTTON_SCANCODE_PUSH).handler(scanCodeMsg) .end();
	}
//	@Override
//	public WxCpConfigStorage getConfig() {
//		// TODO Auto-generated method stub
//		return config;
//	}
//	@Override
//	public WxCpConfigStorage getbyPT(String province,String token) {
//		// TODO Auto-generated method stub	
//		List<WxCpMyConfigStorage> config1=configStorageDao.getbyPT(province,token);
// 		config=config1.get(0);
//		return config;
//	}
	@Override
	public DodemWxCpUser getUser(DodemWxServer server,String code) {
		// TODO Auto-generated method stub
		// 根据code 获取用户信息
		DodemWxCpUser user=null;
		String[] res;
		try {
			res = server.oauth2getUserInfo(code);
			// 返回参数 res 有两个 res【0】 当前 扫码的用户 res【1】 id
			if (res.length > 1) {
				List<DodemWxCpUser> lu = userdao.checkUser(res[0]);
				if(lu.size()>0)
					user=lu.get(0);
				
			}
			for (String re : res) {
				log.info(re);
			}
		} catch (WxErrorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return user;	
	}
	@Override
	public List<WxCpMyConfigStorage> 	getConfigByUserMobile(String mobile,String email,String weixinid){
		return configStorageDao.getConfigByUserMobile(mobile, email, weixinid);
	}
	@Override
	public JSONObject SyncDepartFromWeiXin(DodemWxServer server){
        JSONObject obj = new JSONObject();
	
	try {
	 
 
		// 读取部门信息
		depdao.clearByCorpId(server.getConfig().getCorpId());;
		//userdao.clear();
		List<WxCpDepart> dps =  server.departGet();
	
		// 入库
		depdao.addDeparts(dps,server.getConfig().getCorpId());
		
		for (WxCpDepart dp : dps) {
			// 根据部门 读取部门成员信息
			List<WxCpUser> mbs =  server.userList(dp.getId(), false, 0);
			System.out.println(dp.toString());
		 

			for (WxCpUser mb : mbs) {
				// System.out.println(mb.getWeiXinId()+","+mb.getMobile()+","+mb.getName());
				System.out.println(mb.toJson());
			 
			}
			// 入库
			if (mbs.size() > 0)
				userdao.addUsers(mbs,server.getConfig().getCorpId());
		}
		obj.put("success", true);
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		obj.put("success", false);
	}

	return obj;
}
	//读取可用的user
	@Override
	public WxCpUser getAvailableUser(String code) {
		// TODO Auto-generated method stub
        WxCpUser user =null;
        java.util.Iterator<Entry<String, DodemWxServer>> iter = wxSMAP.entrySet().iterator();
        
    	while (iter.hasNext()) {
    		Map.Entry entry = (Map.Entry) iter.next();
    		String key = (String) entry.getKey();
    		DodemWxServer val = (DodemWxServer) entry.getValue();
    		if(key.contains("real")){
    			  user = getUser(val,code);
    			  if(user!=null)
    				  return user;
    		}
    		 
    	}
	     
		 
		 
		 return user;
		
		
	 
	}
	@Override
	public List<WxCpMyConfigStorage> getAllProvinceInfo(String corpid) {
		
		return configStorageDao.getPorvinceInfo(corpid);
	}
	
	
	 
}
